<template>
  <div class="app-container">
    <el-row :gutter="30">
      <!--用户数据-->
      <el-col style="width: 680px" :xs="15" :sm="18" :md="20" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.blurry"
              clearable
              size="small"
              placeholder="输入名称搜索"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <el-date-picker
              v-model="query.createtime"
              :default-time="['00:00:00','23:59:59']"
              type="daterange"
              range-separator=":"
              size="small"
              class="date-item"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
            <rrOperation :crud="crud" />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="570px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
            <el-form-item label="村组" prop="countygroup">
              <el-input v-model="form.countygroup" />
            </el-form-item>
            <el-form-item label="户属性" prop="attr">
              <el-input v-model.number="form.attr" />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" />
            </el-form-item>
            <el-form-item label="登记人员" prop="record">
              <el-input v-model="form.record" />
            </el-form-item>
            <el-form-item label="家庭编号" prop="familyid">
              <el-input v-model="form.familyid" />
            </el-form-item>
            <el-form-item label="家庭人口数" prop="num">
              <el-input v-model="form.num" />
            </el-form-item>
            <el-form-item label="农业人口数" prop="count">
              <el-input v-model="form.count" />
            </el-form-item>
            <el-form-item label="区域" prop="j_area.id">
              <treeselect
                v-model="form.j_area.id"
                :options="j_areas"
                style="width: 178px"
                placeholder="选择区域"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler" @current-change="handleCurrentChange">
          <el-table-column type="selection" width="60" />
          <el-table-column v-if="columns.visible('countygroup')" width="100" :show-overflow-tooltip="true" prop="countygroup" label="村组" />
          <el-table-column v-if="columns.visible('attr')" width="120" :show-overflow-tooltip="true" prop="attr" label="户属性" />
          <el-table-column v-if="columns.visible('address')" prop="address" label="地址" />
          <el-table-column v-if="columns.visible('record')" :show-overflow-tooltip="true" prop="record" width="100" label="登记人员" />
          <el-table-column v-if="columns.visible('familyid')" :show-overflow-tooltip="true" width="80" prop="familyid" label="家庭编号" />
          <el-table-column v-if="columns.visible('num')" align="center" :show-overflow-tooltip="true" width="80" prop="num" label="家庭人口数" />
          <el-table-column v-if="columns.visible('count')" align="center" :show-overflow-tooltip="true" width="80" prop="count" label="农业人口数" />
          <el-table-column v-if="columns.visible('j_area')" align="center" :show-overflow-tooltip="true" width="100" prop="j_area" label="区域名称">
            <template slot-scope="scope">
              <div>{{ scope.row.j_area.county }}</div>
            </template>
          </el-table-column>
          <el-table-column :formatter="dateFormat" align="center" v-if="columns.visible('createtime')" :show-overflow-tooltip="true" prop="createtime" width="140" label="创建日期" />
          <el-table-column
            v-permission="['admin','family:edit','family:del']"
            label="操作"
            width="125"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
              />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
      <!-- 参合家庭含有的参合农民信息 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7" style="margin-top: 50px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定户主对应的家庭成员" placement="top">
              <span class="family-span">户主对应的家庭成员</span>
            </el-tooltip>
            <el-button
              v-permission="['admin','family:edit']"
              :disabled="!showButton"
              :loading="homeLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveHome"
            >保存</el-button>
          </div>
          <el-tree
            ref="home"
            :data="homes"
            :default-checked-keys="homeIds"
            :props="defaultProps"
            check-strictly
            accordion
            node-key="id"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import crudFamily from '@/api/vocation/family'
  import CRUD, { presenter, header, form, crud } from '@crud/crud'
  import rrOperation from '@crud/RR.operation'
  import crudOperation from '@crud/CRUD.operation'
  import udOperation from '@crud/UD.operation'
  import pagination from '@crud/Pagination'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { getJ_areasTree } from '@/api/common/j_area'
  import moment from 'moment'
  import { getHomeTree } from '@/api/vocation/home'

  // crud交由presenter持有
  const defaultCrud = CRUD({ title: '家庭档案', url: 'api/family', crudMethod: { ...crudFamily }})
  const defaultForm = { id: null, countygroup: null, attr: null, address: null, record: null, familyid: null, num: null, count: null, j_area: { id: null }, createtime: null }
  export default {
    components: { Treeselect, crudOperation, rrOperation, udOperation, pagination },
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    data() {
      return {
        level: 3,
        currentId: 0, homeLoading: false, showButton: false,
        homes: [], homeIds: [],
        height: document.documentElement.clientHeight - 180 + 'px;',
        j_areaName: '',
        j_areas: [],
        j_areaDatas: [],
        defaultProps: { children: 'children', label: 'label' },
        permission: {
          add: ['admin', 'family:add'],
          edit: ['admin', 'family:edit'],
          del: ['admin', 'family:del']
        },
        rules: {

        }
      }
    },
    created() {
      this.$nextTick(() => {
        this.getHomeTree()
        this.getJ_areas()
        this.crud.toQuery()
        this.crud.msg.add = '新增成功'
      })
    },
    mounted: function() {
      const that = this
      window.onresize = function temp() {
        that.height = document.documentElement.clientHeight - 180 + 'px;'
      }
    },
    methods: {
      [CRUD.HOOK.afterRefresh]() {
        this.$refs.home.setCheckedKeys([])
      },
      // 编辑前
      [CRUD.HOOK.beforeToEdit](crud, form) {
      },
      // 提交前做的操作
      [CRUD.HOOK.afterValidateCU](crud) {
      },
      [CRUD.HOOK.afterAddError](crud) {
        this.afterErrorMethod(crud)
      },
      [CRUD.HOOK.afterEditError](crud) {
        this.afterErrorMethod(crud)
      },
      afterErrorMethod(crud) {
      },
      deleteTag(value) {
      },
      // 新增与编辑前做的操作
      [CRUD.HOOK.afterToCU](crud, form) {
        this.getJ_areas()
      },
      // 打开编辑弹窗前做的操作
      [CRUD.HOOK.beforeToEdit](crud, form) {
      },
      // 提交前做的操作
      [CRUD.HOOK.afterValidateCU](crud) {
        if (!crud.form.j_area.id) {
          this.$message({
            message: '区域不能为空',
            type: 'warning'
          })
          return false
        }
        return true
      },
      // 获取弹窗内区域数据
      getJ_areas() {
        getJ_areasTree().then(res => {
          this.j_areas = res
          console.log(this.j_areas)
        })
      },
      // 切换区域
      handleNodeClick(data) {
        if (data.pid === 0) {
          this.query.j_areaid = null
        } else {
          this.query.j_areaid = data.id
        }
        this.crud.toQuery()
      },
      //日期格式化
      dateFormat:function(row,column){
        var date = row[column.property];
        if(date === undefined){return ''};
        return moment(date).format("YYYY-MM-DD")
      },
      // 触发单选
      handleCurrentChange(val) {
        if (val) {
          const _this = this
          // 清空成员表中的选中
          this.$refs.home.setCheckedKeys([])
          // 保存当前的户主id
          this.currentId = val.id
          this.showButton = true
          // 初始化
          this.homeIds = []
          // 菜单数据需要特殊处理
          val.homes.forEach(function(data, index) {
            _this.homeIds.push(data.id)
          })
        }
      },
      //获取所有家庭成员 即参合农民的数据
      getHomeTree() {
        getHomeTree().then(res => {
          this.homes = res
          console.log(this.homes)
        })
      },
      // 保存家庭成员
      saveHome() {
        this.homeLoading = true
        const family = { id: this.currentId, homes: [] }
        // 得到半选的父节点数据，保存起来
        this.$refs.home.getHalfCheckedNodes().forEach(function(data, index) {
          const home = { id: data.id }
          family.homes.push(home)
        })
        // 得到已选中的 key 值
        this.$refs.home.getCheckedKeys().forEach(function(data, index) {
          const home = { id: data }
          family.homes.push(home)
        })
        crudFamily.editHome(family).then(res => {
          this.crud.notify('保存成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.homeLoading = false
          this.update()
        }).catch(err => {
          this.homeLoading = false
          console.log(err.response.data.message)
        })
      },
    }
  }
</script>

<style scoped>
</style>
